package com.mccree.config;

import com.mccree.mapper.UserMapper;
import com.mccree.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.Md5CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * 自定义realm
 */
public class UserRealm extends AuthorizingRealm {


    @Autowired
    UserMapper userMapper;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=====>授权逻辑PrincipalCollection");
        //给资源进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获得当前授权对象
        Subject subject = SecurityUtils.getSubject();
        //拿到认证对象user
        User user = (User) subject.getPrincipal();
        String[] prems = user.getPerms().split(",");
        Set<String> permissions = new HashSet<>();
        for(String prem:prems){
            permissions.add(prem);
        }
        //添加权限
        info.addStringPermissions(permissions);
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了======>认证逻辑AuthenticationToken");
        //获取token并校验
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //模拟数据库取到的用户名和密码
//        String name = "root";
//        String password = "123456";
        //连接真实数据库
        User user = userMapper.queryUserByName(token.getUsername());


        if (user==null){
            //如果用户名不存在，shiro底层会抛出UnknownAccountException，
            // 这里shiro帮我们做了，只需要返回null
            return null;
        }
        //验证密码，我们可以使用AuthenticationInfo的实现类，shiro会帮我们去自动校验密码
        //Object principal 认证对象（可省略）, Object credentials 密码, String realmName 认证名（可省略）
        return new SimpleAuthenticationInfo(user,user.getPwd(),getName());
    }
}
